//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#include <buola/algorithm/gzip.h>
#include <buola/io.h>
#include <zlib.h>

namespace buola {

std::vector<uint8_t> gunzip_buffer(const std::vector<uint8_t> &pIn)
{
    z_stream lZ;
    lZ.next_in=const_cast<uint8_t*>(pIn.data());
    lZ.avail_in=pIn.size();
    lZ.zalloc=nullptr;
    lZ.zfree=nullptr;
    if(inflateInit2(&lZ,31)!=Z_OK) throw XInvalid("error initializing gzip decompression");
    std::vector<uint8_t> lOut(32768);

    lZ.next_out=lOut.data();
    lZ.avail_out=lOut.size();

    while(true)
    {
        int lRet=inflate(&lZ,Z_FINISH);
        msg_info() << lRet << " " << lZ.avail_in << " " << lZ.avail_out << "\n";
        
        if(lRet==Z_STREAM_END)
        {
            lOut.resize(lOut.size()-lZ.avail_out);
            break;
        }
        else if(lRet==Z_OK||lRet==Z_BUF_ERROR)
        {
            size_t lSize=lOut.size();
            lOut.resize(lSize*2);
            lZ.avail_out+=lSize;
            lZ.next_out=lOut.data()+lOut.size()-lZ.avail_out;
        }
        else
        {
            inflateEnd(&lZ);
            throw XInvalid("error in gzip decompression");
        }
    }

    inflateEnd(&lZ);
    
    return lOut;
}
    
/*namespace buola*/ }
